import g4p_controls.*;  // Need G4P library
// You can remove the PeasyCam import if you are not using
// the GViewPeasyCam control or the PeasyCam library.
import peasy.*;

import processing.serial.*;
int lf = 10;      // ASCII linefeed
String inString;  // Input string from serial port
PFont myFont;     // The display font
Serial myPort;    // The serial port:

int pitch, roll, yaw;
boolean is_drawPitchRoll_free = true;
boolean is_drawYaw_free = true;

public void setup(){
  size(1600, 800, JAVA2D);
  smooth();
  createGUI();
  customGUI();
  
  printArray(Serial.list());  // List all the available serial ports:
  myPort = new Serial(this, Serial.list()[0], 115200); // Open the port you are using at the rate you want:
  myPort.bufferUntil(lf);
}

void serialEvent(Serial p) {
  inString = p.readString();
  
  String tmpStr = "";
  for(int i = 0; i < 4; i++) {
    if(inString.charAt(i) == 0x20) { // 0x20 = SPACE
      break;
    }
    tmpStr = tmpStr +inString.charAt(i);
  }
  int value = int(tmpStr);
  
  if(value <= 180) {
    pitch = value;
  }else if(value <= 580) {
    roll = value - 400;
    if(is_drawPitchRoll_free) {
      is_drawPitchRoll_free = false;
      thread("drawPitchRoll");
    }
  }else if(value <= 959) {
    yaw = value - 600;
    if(is_drawYaw_free) {
      is_drawYaw_free = false;
      thread("drawYaw");
    }
  }
}

void drawPitchRoll() {
  pitch_roll_indicator.setValueXY(roll, pitch);
  is_drawPitchRoll_free = true;
}

void drawYaw() {
  yaw_knob.setValue(yaw);
  is_drawYaw_free = true;
}

public void draw(){
  background(230);
}

// Use this method to add additional statements
// to customise the GUI controls
public void customGUI(){

}
